package cn.boy.gui.student;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.boy.adapter.HistoryAdapter;
import cn.boy.domain.Dormitory;
import cn.boy.home.HomeApplication;
import cn.boy.home.R;
import cn.boy.service.HomeService;

public class StudentMarkActivity extends Activity {
	
	private static final String TAG = "StudentMarkActivity";
	HomeApplication app;
	TextView txtMark;
	
	ProgressDialog pd;

	String retValue = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.mark_student);
		
		app = (HomeApplication) getApplicationContext();
		
		txtMark =  (TextView)findViewById(R.id.tv_mark);
		
		loadData();
		
	}
	private void loadData() {
		showDialog();
		new Thread(new Runnable() {
			public void run() {
				try {
					retValue = HomeService.latestMark(app.getStudent().getDormitoryNO());
					if (!retValue.equals("")) {
						sendHandlerMessage(1);
					} else {
						sendHandlerMessage(2);
					}
				} catch (Exception e) {
					Log.e(TAG, e.toString());
					sendHandlerMessage(0);
				}
			}
		}).start();

		
	}

	
	
	private void showDialog() {
		pd = new ProgressDialog(StudentMarkActivity.this);
		pd.setMessage(getResources().getString(R.string.get_dorms_ing));
		pd.show();
	}

	private void sendHandlerMessage(int what) {
		Message msg = handler.obtainMessage(what);
		handler.sendMessage(msg);

	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (pd != null) {
				pd.dismiss();
			}
			switch (msg.what) {
			case 0:
				Toast.makeText(StudentMarkActivity.this,
						R.string.net_unreacgabke, 1).show();
				break;
			case 1:
				try {
					JSONObject obj = new JSONObject(retValue);
					Dormitory dorm = mappingEntity(obj);
					txtMark.setText(dorm.getMark());
				} catch (JSONException e) {
					Log.e(TAG, e.toString());
				}
				break;
			case 2:
				Toast.makeText(StudentMarkActivity.this,
						R.string.get_data_fail, 1).show();
				break;
			}
		}

	};
	

	private Dormitory mappingEntity(JSONObject obj) {
		try {
			String no = obj.getString("no");
			String name = obj.getString("name");
			String mark = obj.getString("mark");
			String date = obj.getString("date");
			Dormitory dorm = new Dormitory(no, name, mark, date);
			return dorm;
		} catch (JSONException e) {
			Log.e(TAG, e.toString());
			return null;
		}
		
	}
}
